package com.love.marriage.identityVerification.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.love.marriage.common.exceptions.SystemException;
import com.love.marriage.common.vo.SecurityUser;
import com.love.marriage.config.ApiSpaceConfig;
import com.love.marriage.identityVerification.entity.IdentityVerification;
import com.love.marriage.identityVerification.mapper.IdentityVerificationMapper;
import com.love.marriage.identityVerification.service.IdentityVerificationService;
import com.love.marriage.identityVerification.vo.IdentityVerificationVo;
import com.love.marriage.utils.StringUtils;
import com.love.marriage.utils.UserUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * description:  身份认证表服务实现类
 * author:       alex
 * createDate:   2024-10-13 09:15:21
 * version:      1.0.0
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class IdentityVerificationServiceImp extends ServiceImpl<IdentityVerificationMapper, IdentityVerification> implements IdentityVerificationService {

    private final IdentityVerificationMapper identityVerificationMapper;

    private final ApiSpaceConfig apiSpaceConfig;

    @Override
    public Page<IdentityVerificationVo> getPage(Long pageNum, Long pageSize, IdentityVerificationVo identityVerificationVo) {
        Page<IdentityVerificationVo> page = new Page<>(pageNum == null ? 1 : pageNum, pageSize == null ? 10 : pageSize);
        return identityVerificationMapper.getPage(page, identityVerificationVo);
    }

    @Override
    public IdentityVerificationVo queryIdentityVerification(Long id) {
        return identityVerificationMapper.queryIdentityVerification(id);
    }

    @Override
    public IdentityVerificationVo queryIdentityVerificationByUserId(Long userId) {
        return identityVerificationMapper.queryIdentityVerificationByUserId(userId);
    }

    @Override
    public IdentityVerificationVo addIdentityVerification(IdentityVerificationVo identityVerificationVo) {
        IdentityVerification identityVerification = new IdentityVerification();
        BeanUtils.copyProperties(identityVerificationVo, identityVerification);
        identityVerificationMapper.insert(identityVerification);
        IdentityVerificationVo res = new IdentityVerificationVo();
        BeanUtils.copyProperties(identityVerification, res);
        return res;
    }

    @Override
    public IdentityVerificationVo updateIdentityVerification(IdentityVerificationVo identityVerificationVo) {
        IdentityVerification identityVerification = new IdentityVerification();
        BeanUtils.copyProperties(identityVerificationVo, identityVerification);
        identityVerificationMapper.updateById(identityVerification);
        return identityVerificationVo;
    }

    @Override
    public Boolean deleteIdentityVerification(String ids) {
        if (StringUtils.isEmpty(ids)) {
            return true;
        }
        List<String> idArr = Arrays.asList(ids.split(","));
        identityVerificationMapper.deleteBatchIds(idArr);
        return true;
    }

    @Override
    public IdentityVerificationVo identityVerification(IdentityVerificationVo identityVerificationVo) throws Exception {
        // 校验当前数据是否实名认证过
        IdentityVerificationVo search = new IdentityVerificationVo();
        search.setIdCardNumber(identityVerificationVo.getIdCardNumber());
        search.setName(identityVerificationVo.getName());
        List<IdentityVerificationVo> db = identityVerificationMapper.queryIdentityVerificationInfo(search);
        if (db != null && !db.isEmpty() && (db.size() > 1 || !Objects.equals(db.get(0).getUserId(), identityVerificationVo.getUserId()))) {
            throw new SystemException("4000019", "该身份证号已被其他用户认证");
        }
        // 实名认证
        JsonNode verify = verify(identityVerificationVo.getIdCardNumber(), identityVerificationVo.getName());
        String code = verify.has("code") ? verify.get("code").asText() : "500";
        if (!"0".equals(code)) {
            throw new SystemException("4000017", verify.has("message") ? verify.get("message").asText() : "认证失败！");
        }
        if (verify.has("data")) {
            JsonNode dataNode = verify.get("data");
            boolean isValid = dataNode.has("valid") && dataNode.get("valid").asBoolean();
            if (!isValid) {
                // 数据校验失败的逻辑，可以通过获取 incorrect 和 message 字段来进一步处理
                int incorrect = dataNode.has("incorrect") ? dataNode.get("incorrect").asInt() : -1;
                String message = dataNode.has("message") ? dataNode.get("message").asText() : "校验失败";
                System.out.println("验证失败: " + message + "，错误码: " + incorrect);
                throw new SystemException("4000017", "真实姓名与身份证号" + message);
            }
        } else {
            // `data` 节点不存在时的处理逻辑
            throw new SystemException("4000017", "认证失败");
        }
        IdentityVerificationVo dbInfo = queryIdentityVerificationByUserId(identityVerificationVo.getUserId());
        if (dbInfo == null) {
            dbInfo = new IdentityVerificationVo();
            SecurityUser loginUser = UserUtils.getLoginUser();
            if (loginUser != null && dbInfo.getUserId() == null) {
                dbInfo.setUserId(loginUser.getId());
            }
        }
        dbInfo.setName(identityVerificationVo.getName());
        dbInfo.setIdCardNumber(identityVerificationVo.getIdCardNumber());
        dbInfo.setVerificationCode("200");
        dbInfo.setVerificationInfo("认证成功");
        IdentityVerification identityVerification = new IdentityVerification();
        BeanUtils.copyProperties(dbInfo, identityVerification);
        identityVerification.insertOrUpdate();
        IdentityVerificationVo res = new IdentityVerificationVo();
        BeanUtils.copyProperties(identityVerification, res);
        return res;
    }

    public JsonNode verify(String idCardNumber, String name) throws Exception {
        OkHttpClient client = new OkHttpClient().newBuilder().build();
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");

        // Build the request body with real name and id card number
        RequestBody body = RequestBody.create(mediaType, "realname=" + name + "&idcard=" + idCardNumber);
        // Build the request
        Request request = new Request.Builder()
                .url(apiSpaceConfig.getUrl())
                .method("POST", body)
                .addHeader("X-APISpace-Token", apiSpaceConfig.getToken())
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();

        // Execute the request
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new SystemException("4000017", "身份认证失败！");
            }
            ObjectMapper objectMapper = new ObjectMapper();
            String responseBody = response.body().string();
            return objectMapper.readTree(responseBody);
        }
    }
}
